//
//  UIImage+Size.m
//  UIKit_Category
//
//  Created by Elvis on 2017/8/17.
//  Copyright © 2017年 Elvis. All rights reserved.
//

#import "UIImage+Size.h"

@implementation UIImage (Size)

- (instancetype)scaleImageWithWidth:(CGFloat)width {
    if (width > self.size.width) {
        return self;
    }
    CGFloat height = self.size.height * width / self.size.width;
    CGRect rect = CGRectMake(0, 0, width, height);
    /** 开启上下文 */
    UIGraphicsBeginImageContext(rect.size);
    /** 绘制 */
    [self drawInRect:rect];
    /** 取结果 */
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    /** 关闭上下文 */
    UIGraphicsEndImageContext();
    return image;
}

- (UIImage *)clipWithImageRect:(CGRect)clipRect{
    
    // 开启位图上下文
    UIGraphicsBeginImageContext(clipRect.size);
    
    // 绘制图片
    [self drawInRect:CGRectMake(0,0,clipRect.size.width,clipRect.size.height)];
    
    // 获取当前图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 关闭上下文
    UIGraphicsEndImageContext();
    
    return newImage;
    
}

//返回裁剪区域图片,返回还是原图大小,除图片以外区域清空

- (UIImage *)clipWithclipRect:(CGRect)clipRect{
    
    // 开启位图上下文
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0);
    
    // 设置裁剪区域
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:clipRect];
    [path addClip];
    
    // 绘制图片
    [self drawInRect:clipRect];
    
    // 获取当前图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    // 关闭上下文
    UIGraphicsEndImageContext();
    
    return image;
    
}

- (UIImage *)setImageWithCornerRadius:(CGFloat)radius Size:(CGSize)sizeToFit{
    
    CGRect frame = CGRectMake(0, 0, sizeToFit.width, sizeToFit.height);
    
    // 开启位图上下文
    UIGraphicsBeginImageContextWithOptions(frame.size, NO, [UIScreen mainScreen].scale);
    
    // 获取当前上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // 设置路径
    UIBezierPath *bezier = [UIBezierPath bezierPathWithRoundedRect:frame byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(radius, radius)];
    CGContextAddPath(context, bezier.CGPath);
    CGContextClip(context);
    
    // 绘制图片
    [self drawInRect:frame];
    CGContextDrawPath(context, kCGPathFillStroke);
    
    // 获取当前图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭上下文
    UIGraphicsEndImageContext();
    
    return image;
}

@end
